[% setvar title Interfaces for linking C objects into perlsubs %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Interfaces for linking C objects into perlsubs</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: David Nicol &lt;<a href='mailto:perl6rfc@davidnicol.com'>perl6rfc@davidnicol.com</a>&gt;
  Date: 7 Aug 2000
  Mailing List: <a href='mailto:perl6-internals@perl.org'>perl6-internals@perl.org</a>
  Number: 61
  Version: 2
  Status: Developing</pre>
<a name='ABSTRACT'></a><h1>ABSTRACT</h1>
<p><code>XS</code>, the set of C macros and structures, is a considerable
barrier to writing extensions of Perl in the C language.  While
not replacing XS, this document specifies easier ways to
integrate a C object file (.o) into a perl program, from the
point of view of a perl user wishing to integrate a well defined
and well behaved C program into a perl program in a more direct
way than a <code>system</code> call.</p>
<p><code>XS</code> is an excellent medium for sharing the glory of the internals
of Perl with the C programming community.  It is hoped that the
interface deescribed herein will become an excellent medium for
sharing the glory of the internals of well-written C libraries
with the Perl programming community.</p>
<p>This document is not precisely concerned with the details of the
implementation
of the interfaces it specifies, beyond a general attempt to restrict
itself to the possible.</p>
<p>The <code>use redirect</code> pragma is introduced to allow the external code
to only inherit the running programs file handles that the programmer
wants it to inherit.</p>
<a name='SUMMARY'></a><h1>SUMMARY</h1>
<pre>	use externalh @h_files or die;

	sub callmain{

	   my use redirect STDIN &lt; $InputData;

	   my use redirect STDOUT &gt; PREVIOUSLY_OPENED_HANDLE;

	   $value = use externalc @object_files;

	};

	use externalspace $name_of_the_space;

	tie %cstruct, externalc, $StructDefinition;
	
	%cstruct = unpack( $StructDefinition, $Structure );

	$Structure = pack( $StructDefinition, %cstruct );</pre>
<a name='DESCRIPTION'></a><h1>DESCRIPTION</h1>
<p>This document proposes a set of standard interfaces for linking
compiled (or assembled) object code directly into one's Perl program.</p>
<p>Currently, XS is a large enough additional layer, another ocean of
knowledge, that it is easier to define one's C code into
well behaved utilities and invoke them in backticks than to
convert a stand-alone utility into an XS module.  Rewriting XS
is part of the perl6 mandate.  This RFC is an attempt to suggest
what one alternative would look like.</p>
<a name='default to the main(int argc, char* argv[]) interface in C'></a><h2>default to the <code>main(int argc, char* argv[])</code> interface in C</h2>
<p>C programs accept the knowledge of their run-time command line arguments
via two arguments that are passed to the program's <code>main</code> function.</p>
<p>In the absence of other data provided via the <code>externalh</code> method,
the <code>@_</code> array will be converted for use with this linkage.</p>
<a name='example of using use externalc'></a><h2>example of using <code>use externalc</code></h2>
<p>Through use of the <code>externalc</code> use pragma, a set of compiled .o files
are linked into the program at compile time, and offered
the current scope's <code>@_</code>, converted into scalars, as a <i>count,values</i> pair,
if and when the execution path hits that point.</p>
<p>A mechanism must be selected to support gathering the output and
input of a C program as well, something like shell redirects.  The
<code>use redirect</code> is a placeholder for a system to be announced by the
group working on <i>file handle object</i> issues.</p>
<pre>	sub DatabaseAccess{

		# place to hold the output
		my $tooloutput;	

		# my: redirection will only last until end of scope
			# are not all &quot;use&quot; inside things thusly scoped?
		# no, what if you want a subroutine that redirects?
			# Oh.  Right.  Must require the scoping operator.
		# use redirect: very similar to shell redirection
		my use redirect STDOUT &gt; $tooloutput ;   

		my $retval= use externalc qw(
			/opt/database/accesstool/src/authen.o
			/opt/database/accesstool/src/author.o
			/opt/database/accesstool/src/base64.o
			/opt/database/accesstool/src/choose_authen.o
			/opt/database/accesstool/src/daves.o
			/opt/database/accesstool/src/do_acct.o
			/opt/database/accesstool/src/encrypt.o
			/opt/database/accesstool/src/hash.o
			/opt/database/accesstool/src/hyperauth.o
			/opt/database/accesstool/src/programs.o
			/opt/database/accesstool/src/pw.o
			/opt/database/accesstool/src/pwlib.o
			/opt/database/accesstool/src/smbencrypt.o
			/opt/database/accesstool/src/smbutil.o
		);

		# with &quot;main&quot; linkage we have &quot;0 is success&quot; semantics
		$retval and die &quot;database access tool failed. Erno: $retval&quot;;

		$tooloutput;

	};</pre>
<a name='why not use backticks?'></a><h2>why not use backticks?</h2>
<p>Current practice in this kind of situation is to fully compile
the C program, then write something
like this:</p>
<pre>	sub DatabaseAccess{
		`/opt/database/accesstool @_`;
	};</pre>
<p>There is nothing wrong with this, and it will continue to
work reliably.</p>
<a name='Finer control over importing C functions is provided using the use external function pragma'></a><h2>Finer control over importing C functions is provided using the <code>use external function</code> pragma</h2>
<p>Instead of importing whole programs, we would like to
be able to access arbitrary functions inside arbitrary
pieces of external code, and let perl keep track of a lot
of the housekeeping involved in doing that with a C program.</p>
<a name='the use external mainroutine pragma'></a><h2>the <code>use external mainroutine</code> pragma</h2>
<p><code>use external*</code> can offer more flexibility than <i>merely</i>
extending perl virtual forking to programs which ordinarily would
run in an operating system defined process space. (that is, instead
of calling <code>system</code>).</p>
<p>The name of the
main routine could be changed to something other than <code>main</code>
through manipulation of the <code>use external mainroutine</code> pragma,</p>
<pre>
	use externalh qw(
		/opt/database/accesstool/src/accesstool.h
	);
	use external mainroutine pwverify;
	use externalc;</pre>
<p>Since we have not changed the external name space, <code>externalc</code> will be linking
with the same pile of .o files from last time.</p>
<a name='the use externalh pragma'></a><h2>the <code>use externalh</code> pragma</h2>
<p>The <code>use externalh</code> pragma reads in C header files, with the function
definitions used here, so that <code>externalc</code> can perform reasonable
transformations between the perl data in <code>@_</code> and the arguments specified
in them.</p>
<a name='externalc tie classnames'></a><h2><code>externalc</code> tie classnames</h2>
<p>Data structures in C, and other languages that use offsets into
fixed-size records to differentiate size-limited fields (which are,
of course, vulnerable to being overrun) are defined with language-specific
data structure definition notations.</p>
<p>Using the perl5 <code>tie</code> operator it would not be difficult to create
a class which would allow access into a particular structure, using
<code>substr</code> and <code>unpack</code> to extract the fields, and returning undef or
even dying (tie-time option) when attempt is made to access a field
which is not named in the structure definition.</p>
<p>This process could even be automated, and a C-Header-File-to-perl-tiable-class-definition package would be right at home on the CPAN scripts listing.</p>
<pre>	tie %cstruct, externalc, $StructDefinition;</pre>
<p>would then tie %cstruct to the structure definition described
in <code>$StructDefinition</code>.  This could be, in the same way of
regular expressions, either a text string or a pre-parsed structure
definition in later releases of perl6.</p>
<p>After being so tied, %cstruct can accept value assignment from
a scalar holding a defined structure and will have its fields instantly
filled out:</p>
<pre>
	# New in perl 6 -- by popular demand, fixed length records!
	$FixedInputRecordLength = length($StructDefinition);

	while(%cstruct = &lt;&gt;){	# new in perl 6: &quot;tie&quot; traps assignment to hash
		$Totalpoints += $cstruct{points}
	};</pre>
<p>Perl6 variables will have type and range checking built into them, and
a tied external variable will inherit the limitations of the context it
is being imported from, something you don't get with a Perl5 <code>unpack</code>.</p>
<a name='more fun with structure definitions'></a><h2>more fun with structure definitions</h2>
<p>If we accept structure definitions into our language, as something
a little stronger than <code>pack</code> templates, these two snippets of
code make sense:</p>
<pre>
	%cstruct = unpack( $StructDefinition, $Structure );

	$Structure = pack( $StructDefinition, %cstruct );</pre>
<p>The information carried in a structure definition, regardless of what
language it is imported from, will include:</p>
<ul>
<li><a name='field names =item * field ranges =item * field types (may include range here) =item * offsets into structure'></a>field names
=item *
field ranges
=item *
field types (may include range here)
=item *
offsets into structure</li>
</ul>
<p>Like other aspects of perl, as much as possible will be determined
and optimised away at compile time, while general constructs that
can handle arbitrary inputs will remain for run time binding.</p>
<a name='type checking'></a><h2>type checking</h2>
<p>So, a compile-time compatability table could be maintained, minimizing
the amount of run-type type checking that must be done.  A paranoid
mode would have to be maintained for those who are worried about the
ultrasneaky violating type check rules.</p>
<a name='Instead of package space, external spaces use externalnamespace'></a><h2>Instead of package space, external spaces <code>use externalnamespace</code></h2>
<p>It may be possible to extend the lines around a perl5 package
to work for insulating different external packages being imported into
the same perl program, so that each package can only have one
importable package.</p>
<p>Or, external name spaces can be created with <code>use externalspace</code>
which operates analogously to <code>package</code> in perl5.</p>
<p>Since the wrapping of external functions into perlsubs
will be done in Perl, keeping one external name
space per package forces all access functions for a set of
object files to share the same module.</p>
<a name='other languages'></a><h2>other languages</h2>
<p>Adding additional external* pragmata to support other sorts
of objects, such  as system libraries, will happen.</p>
<a name='IMPLEMENTATION'></a><h1>IMPLEMENTATION</h1>
<a name='getting this to work'></a><h2>getting this to work</h2>
<p>Getting this to work will require knowledge of how linkers
link.  I believe that all platforms support compilation in parts,
and the perl program is itself compiled in parts, so this
extension, although challenging to describe, may be trivial to
implement, or may require perl carrying around its own portable
C library, which it pretty much does already.</p>
<p>The automatic translation between Perl scalar data and C data
structures will be necessarily partial.  Advanced conversions may
be done on the perl side with some to-be-determined packing functions,
for instance.</p>
<a name='Compatibility with legacy code'></a><h2>Compatibility with legacy code</h2>
<p>There is enough room in the perl5 syntaces
for including outside code that no new words will need to be
reserved, not counting the <code>use external*</code> pragmata as reserved words.</p>
<p>The stuff about structure definitions and <code>%TiedHash = $BinaryStructure</code>
would not be possible to emulate in perl5 as I understand it.</p>
<a name='Backwards Compatibility'></a><h2>Backwards Compatibility</h2>
<p>It is very possible that most of the extensions can
be implemented with simple wrappers in XS, for
integrating the new use pragmata into perl5.  And
we keep XS, too, for legacy modules and use by the courageous.</p>
<a name='New Directions'></a><h2>New Directions</h2>
<p>With threads and the new internal fork (whatever it's called)
perl seems to be subsuming more and more of the operating system.
By bringing the linker inside perl, we may be getting closer to
radical compatibility modes in which platform independence could
be offered by setting up portable emulation environments, so that
instead of BSD having a working Linux emulation mode, perl could
have a working linux emulation mode which would run anywhere (as long
as the program running in the environment did not try to do something
outside the realm of what perl can interact with) or perl might
aid projects such as WINE in new ways.</p>
<a name='REFERENCES'></a><h1>REFERENCES</h1>
<p>/usr/lib/perl5/5.00503/pod/perlxs.pod was looked at
to reverify that XS is frighteningly complex.</p>
</div>
